/*
 * Copyright 2012-2013 EZC Group S.A. RCS Luxembourg B140949
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.yobidrive.y3.v1.client.http.handlers;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.yobidrive.y3.http.HttpResponseHandler;
import com.yobidrive.y3.v1.model.RequestChallengeResult;


public class RequestChallengeResponseHandler extends HttpResponseHandler<RequestChallengeResult>{

	static private final Logger logger = Logger.getLogger(RequestChallengeResponseHandler.class);
	
	@Override
	/**
	 * Response to requestchallenge is an XML string containing the challenge object.
	 * <challenge>
	 * 		<username>UserName</username>
	 * 		<realm></realm> 
	 * 		<nonce>cvdsfgdCVqsfdsqfsd</nonce>
	 * 		<validity>20120717130719</validity> 
	 * 		<signature>add9481c0507a0fd1230473f739a8189ff8e3ec2884144cb83331a57f1da46d08642420b634dea1299cd53a3bc4be1feea87d025b8ae789e861f381d5bbfe627</signature> 
	 * </challenge> 
	 * 
	 */
	public RequestChallengeResult handleResponse(HttpResponse response)
			throws ClientProtocolException, IOException {
		
		//Call super to handle every error messages
		super.handleResponse(response);
		
		//Parse XML response
		RequestChallengeResult result = new RequestChallengeResult();
		HttpEntity entity = response.getEntity();
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(entity.getContent());
			result.challenge = (Element) doc.getDocumentElement();
		} catch (Exception ex) {
			logger.error("Error handling response",ex);
			return null;
		}
		
		return result;
	}

	
	
}
